package com.lihua.newideas.controller;

import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageInfo;
import com.lihua.newideas.pojo.JsonResult;
import com.lihua.newideas.pojo.MyUser;
import com.lihua.newideas.pojo.UploadSystem;
import com.lihua.newideas.pojo.UploadUser;
import com.lihua.newideas.service.MyUserService;
import com.lihua.newideas.service.UploadService;
import com.lihua.newideas.service.UploadUserService;
import com.lihua.newideas.uploadUtil.UploadUtil;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

@Controller
public class UploadController {

    @Autowired
    private UploadService uploadService;

    @Autowired
    private UploadUserService uploadUserService;

//    @Autowired
//    private MyUserService myUserService;



    //    查询上传的文件
    /*page 第几页
    * limit 一页有多少条数据
    * */
    @RequestMapping("/goUploadView")
    public String goUploadView(Model model,
                               @RequestParam(value = "page", defaultValue = "1") int page,
                               @RequestParam(value = "limit", defaultValue = "8") int limit) {
        PageInfo<UploadSystem> lists = uploadService.getFileAll(page, limit);
//        System.out.println(lists.toString());
//        System.out.println(lists.getList().toArray());
//        String userPath = System.getProperties().getProperty("user.home") + "/UploadSystem/";
//        model.addAttribute("userPath",userPath);
        model.addAttribute("info", lists);
//       加载上传页面
        return "admin/upload_system";
    }

    /*用户上传图片视图显示
    * */
    @RequestMapping("/goUploadUserView/{userName}")
    public String goUploadUserView(Model model,@PathVariable("userName") String userName,
                                   @RequestParam(value = "page", defaultValue = "1") int page,
                                   @RequestParam(value = "limit", defaultValue = "8") int limit) {
        System.out.println("goUploadUserView:"+userName);
        PageInfo<UploadUser> lists = uploadUserService.getFileAll(userName,page, limit);
//        System.out.println(lists.toString());
//        System.out.println(lists.getList().toArray());
//        String userPath = System.getProperties().getProperty("user.home") + "/UploadSystem/";
//        model.addAttribute("userPath",userPath);
        model.addAttribute("uploadType","uploadUser"); //标志位，标志是用户上传操作
        model.addAttribute("info", lists);

        return "admin/upload_system";
    }

    /*用户上传图片
     * */
    @RequestMapping("/uploadUserImg/{userName}")
    @ResponseBody
    public JsonResult uploadUserImg(@PathVariable("userName") String userName , @RequestParam(value = "file") MultipartFile file, HttpServletRequest request){
        System.out.println("uploadUserImg:"+userName);
        if (userName!=null){
            JsonResult newIdeasFile = upload(userName,file, request, "user");
            return newIdeasFile;
        }else {
            return new JsonResult(false,"用户信息错误");
        }

    }

//    上传文件
    @RequestMapping("/uploadFile")
    @ResponseBody
    public JsonResult uploadFile(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        /*
        * upload 封装的函数
        * */
        JsonResult newIdeasFile = upload(null,file, request, "admin");
        return newIdeasFile;

    }



    public JsonResult  upload(String userName, MultipartFile file, HttpServletRequest request,String filePath){
        if(!file.isEmpty()){
            try {
                // 获取用户目录
                String userPath = System.getProperties().getProperty("user.home") +"/newIdeasFile/";
                // 保存目录
                StringBuffer hold = new StringBuffer("upload/"+filePath+"/");
                // 获取时间，以年月创建目录
                Date date = DateUtil.date();
                hold.append(DateUtil.thisYear()).append("/").append(DateUtil.thisMonth() + 1).append("/");
                File mediaPath = new File(userPath, hold.toString());
                // 如果没有该目录则创建
                if (!mediaPath.exists()) {
                    mediaPath.mkdirs();
                }
                System.out.println("路径++++++" + mediaPath);
                SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss"); //创建时间格式
                // 生成文件名称
                String nameSuffix = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."))
                        .replaceAll(" ", "_").replaceAll(",", "") + format.format(DateUtil.date())
                        + new Random().nextInt(1000);
                // 文件后缀
                String fileSuffix = file.getOriginalFilename()
                        .substring(file.getOriginalFilename().lastIndexOf(".") + 1);
                // 上传文件名加后缀
                String fileName = nameSuffix + "." + fileSuffix;
                // 转存文件
                file.transferTo(new File(mediaPath.toString(), fileName));

                // 原图片路径
                StringBuffer originalPath = new StringBuffer();
                originalPath.append(mediaPath.getAbsolutePath()).append("/").append(fileName);
                // 压缩图片路径
                StringBuffer compressPath = new StringBuffer();
                compressPath.append(mediaPath.getAbsolutePath()).append("/").append(nameSuffix).append("_small.")
                        .append(fileSuffix);
                // 压缩图片
                Thumbnails.of(originalPath.toString()).size(256, 256).keepAspectRatio(false).toFile(compressPath.toString());
                // 原图数据库路径
                StringBuffer originalDataPath = new StringBuffer();
                originalDataPath.append("/").append(hold).append(fileName);
                // 压缩图数据库路径
                StringBuffer compressDataPath = new StringBuffer();
                compressDataPath.append("/").append(hold).append(nameSuffix).append("_small.").append(fileSuffix);

                if (userName==null){
//                    UploadSystem uploadSystem =  (UploadSystem)object;
                    UploadSystem uploadSystem = new UploadSystem();
                    uploadSystem.setPictureName(fileName);
                    uploadSystem.setPicturePath(originalDataPath.toString());
                    uploadSystem.setPictureType(file.getContentType());
                    uploadSystem.setPictureCreateDate(date);
                    uploadSystem.setPictureSuffix(new StringBuffer().append(".").append(fileSuffix).toString());
                    uploadSystem.setPictureSmallPath(compressDataPath.toString());
                    uploadSystem.setPictureWh(UploadUtil.getImageWh(new File(mediaPath.toString() + "/" + fileName)));
                    uploadSystem.setPictureSize(UploadUtil.parseSize(new File(mediaPath.toString() + "/" + fileName).length()));
                    uploadService.save(uploadSystem);
                }else {
                    UploadUser uploadUser = new UploadUser();
                    uploadUser.setUserName(userName);
                    uploadUser.setPictureName(fileName);
                    uploadUser.setPicturePath(originalDataPath.toString());
                    uploadUser.setPictureType(file.getContentType());
                    uploadUser.setPictureCreateDate(date);
                    uploadUser.setPictureSuffix(new StringBuffer().append(".").append(fileSuffix).toString());
                    uploadUser.setPictureSmallPath(compressDataPath.toString());
                    uploadUser.setPictureWh(UploadUtil.getImageWh(new File(mediaPath.toString() + "/" + fileName)));
                    uploadUser.setPictureSize(UploadUtil.parseSize(new File(mediaPath.toString() + "/" + fileName).length()));
                    uploadUserService.save(uploadUser);
                }
                return new JsonResult(true,originalDataPath.toString());   //上传后必须以这种方式返回文件路径，否则即使上传成功，前台也会显示失败
            }catch (Exception e){
                System.out.println("上传附件错误" + e.getMessage());
                return new JsonResult(false,"失败");
            }

        }else {
            //       加载上传页面
            return new JsonResult(false,"没有选择文件");
        }
    }

}
